//
//  UIFont+CYFont.m
//  cyjf
//
//  Created by tauCross on 2017/5/18.
//  Copyright © 2017年 Auto Financing. All rights reserved.
//

#import "UIFont+CYFont.h"



@implementation UIFont (CYFont)

+ (void)load
{
    {
        Method oriMethod = class_getClassMethod([[UIFont new] class], @selector(systemFontOfSize:));
        Method cyMethod = class_getClassMethod([[UIFont new] class], @selector(cy_systemFontOfSize:));
        method_exchangeImplementations(oriMethod, cyMethod);
    }
    {
        Method oriMethod = class_getClassMethod([[UIFont new] class], @selector(systemFontOfSize:weight:));
        Method cyMethod = class_getClassMethod([[UIFont new] class], @selector(cy_systemFontOfSize:weight:));
        method_exchangeImplementations(oriMethod, cyMethod);
    }
}

+ (UIFont *)cy_systemFontOfSize:(CGFloat)size
{
    UIFont *font = [UIFont fontWithName:[self fontNames][@(UIFontWeightRegular)] size:size];
    if(font)
    {
        return font;
    }
    return [self cy_systemFontOfSize:size];
}

+ (UIFont *)cy_systemFontOfSize:(CGFloat)size weight:(CGFloat)weight
{
    NSString *fontName = [[self fontNames] objectForKey:@(weight)];
    if(fontName)
    {
        UIFont *font = [UIFont fontWithName:fontName size:size];
        if(font)
        {
            return font;
        }
    }
    return [UIFont cy_systemFontOfSize:size weight:weight];
}

+ (NSDictionary *)fontNames
{
    static NSDictionary *fontNames = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *regular = nil;
        if(IOS10_OR_LATER)
        {
            regular = @".SFUIDisplay";
        }
        else
        {
            regular = @".SFUIDisplay-Regular";
        }
        fontNames = @{@(UIFontWeightUltraLight) : @".SFUIDisplay-Ultralight",
                      @(UIFontWeightThin) : @".SFUIDisplay-Thin",
                      @(UIFontWeightLight) : @".SFUIDisplay-Light",
                      @(UIFontWeightRegular) : regular,
                      @(UIFontWeightMedium) : @".SFUIDisplay-Medium",
                      @(UIFontWeightSemibold) : @".SFUIDisplay-Semibold",
                      @(UIFontWeightBold) : @".SFUIDisplay-Bold",
                      @(UIFontWeightHeavy) : @".SFUIDisplay-Heavy",
                      @(UIFontWeightBlack) : @".SFUIDisplay-Black"};
    });
    return fontNames;
}

@end
